/*
 * author      : 吴中勤 
 * date        : 2018/8/16
 * description : moby事件分发, 此controller进行接收处理
 */

package com.deepexi.adapter.rest.moby;

import com.deepexi.adapter.common.CommonUtils;
import com.deepexi.adapter.converter.ConverterManagerImpl;
import com.deepexi.adapter.converter.sap.MobyEventBodyCheck;
import com.deepexi.adapter.converter.sap.order.OrderService;
import com.deepexi.adapter.facade.moby.request.MobyEventBody;
import com.google.gson.JsonSyntaxException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "/api/v1/moby/event")
public class MobyEventReceiveController {

    private static final Logger logger = LoggerFactory.getLogger(MobyEventReceiveController.class);


    @Autowired
    private OrderService orderService;

    @Autowired
    private ConverterManagerImpl converterManager;

    @Autowired
    private MobyEventBodyCheck checker;

//    private MobyEventHandler eventHandler;
//
//    @PostConstruct
//    public void initAfterSetup() {
//        this.eventHandler = converterManager.getDefaultMobyEventHandler();
//    }

    /** 测试接口 */
    @ResponseBody
    @RequestMapping(value = {"/hello"}, method = {RequestMethod.GET})
    public String test1() throws Exception {
        return "hello";
    }

    /** 接口数据有效性检测 */
    @ResponseBody
    @RequestMapping(value = {"/inspect"}, method = {RequestMethod.POST})
    public String eventCheck(@RequestBody String msg) {
        try {
            // 拆包
            // {
            //      body:{},
            //      "className":"com.deepexi.trade.domain.msg.MsgVO",
            //      "msgId":"d3af83fd15e44339b0531f600935"
            // }
            JSONObject jsonObject = new JSONObject(msg);
            String msgBody = jsonObject.getString("body");
            if (null == msgBody) throw new JSONException("必须包含 body节点");

            MobyEventBody body = CommonUtils.jsonString2Obj(msgBody, MobyEventBody.class);
            StringBuilder sb = new StringBuilder(1024);
            if (!checker.checkMobyEventBody(body, sb)) {
                logger.error("消息未能通过 有效性校验");
                logger.error(sb.toString());
                return sb.toString();
            }
        } catch (JSONException ex) {
            return "消息体不符合规范, 必须有body节点";
        } catch (JsonSyntaxException ex) {
            return ("消息体不能转换为 MobyEventBody, msg=" + msg);
        }

        return "消息题检测通过";
    }

    /** 这个接口仅供测试时解锁车辆 */
    @ResponseBody
    @RequestMapping(value = {"/unlock"}, method = {RequestMethod.GET})
    public String unlock(@RequestParam("id") String mobyOrderId) {
        try {
            orderService.onVehicleUnlockedById(mobyOrderId);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("解锁失败,{}", ex);
        }

        return "解锁OK";
    }

    /**
     * 这个接口仅供测试时 采购物料
     * http://localhost:8001/adapter/api/v1/moby/event/tobuy?id=xxx&line=xxxx
     */
    @ResponseBody
    @RequestMapping(value = {"/tobuy"}, method = {RequestMethod.GET})
    public String purchaseItem(@RequestParam("id") String mobyOrderId, @RequestParam("line") String line) {
        try {
            orderService.onPurchaseItem(mobyOrderId, line);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("采购物料,{}", ex);
        }

        return "采购物料 OK";
    }
}
